using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Lonewolf.Entity;
using Lonewolf.IService;
using Lonewolf.Service;
using Lonewolf.WebApp.Controllers;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Swashbuckle.AspNetCore.Swagger;

namespace Lonewolf.WebApp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public static IContainer ApplicationContainer { get; private set; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)//IServiceProvider
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            //替换控制器所有者
            //此举用于IOC属性注入，使用构造函数注入可注释本句
            services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            //注册Cookie认证
            services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            }).AddCookie(options => { });
            //加入api接口文档
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Title = "ShuHan API V1.0",
                    Version = "v1.0",
                    License = new License
                    {
                        Name = "MIT",
                        Url = ""
                    },
                    Contact = new Contact
                    {
                        Email = "642956057@qq.com",
                        Name = "Lonewolf",
                        Url = "https://www.baidu.cn"
                    }
                });
            });
            //这个方法它默认的生命周期为ServiceLifetime.Scoped
            //Server=localhost;Port=3306;Database=Lonewolf_WebApp; User=root;Password=12131124;sslmode=none;
            //Server=47.94.7.36;Port=3306;Database=Lonewolf_WebApp; User=root;Password=Hzx12131124;sslmode=none;
            //Mysql
            services.AddDbContextPool<EFDbContext>(options => options.UseMySql("Server=47.94.7.36;Port=3306;Database=Lonewolf_WebApp; User=root;Password=Hzx12131124;sslmode=none;"));
            //MSsql
            //var connectionString = Configuration.GetConnectionString("ECMSConnection");
            //services.AddDbContext<EFDbContext>(opt => opt.UseSqlServer(connectionString, p => p.MigrationsAssembly("ECMS.Domain")));
            //注册IUnitOfWork的时候使用AddScoped方法，将其生命周期限定为Scoped，就能保证每次请求都是共用同一个对象
            services.AddScoped<IUnitOfWork, UnitOfWork<EFDbContext>>();//注入UOW依赖，确保每次请求都是同一个对象
            //注册ioc
            var builder = new ContainerBuilder();//实例化 AutoFac  容器            
            builder.Populate(services);
            //模块化注入
            builder.RegisterModule<AutoFacConfig>();
            //属性注入控制器
            //builder.RegisterType<HomeController>().PropertiesAutowired();
            ApplicationContainer = builder.Build();
            return new AutofacServiceProvider(ApplicationContainer);//第三方IOC接管 core内置DI容器

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "ShuHan API Document V1.0");
            });
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            //注册Cooike中间件
            app.UseAuthentication();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
            
            //autofac
            //程序停止调用函数
            appLifetime.ApplicationStopped.Register(() => { ApplicationContainer.Dispose(); });
        }
    }
}
